package com.itheima.bos.web.common;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

	// 模型驱动
	protected T model;

	@Override
	public T getModel() {

		return model;
	}

	// 构造器,给model实例化
	public BaseAction() {
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		// 获取第一个泛型参数
		ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
		Class<T> modelClass = (Class<T>) parameterizedType
				.getActualTypeArguments()[0];
		try {
			model = modelClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("模型构造失败...");
		}
	}

	// 分页查询参数
	protected int page;
	protected int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	// 将数据转换成json数据并压进值栈顶
	protected void pushPageDataToValueStack(Page<T> pageData) {
		// 将查询到的数据转换成对应的json数据
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pageData.getTotalElements());
		map.put("rows", pageData.getContent());
		// 将查询到的数据压进栈
		ActionContext.getContext().getValueStack().push(map);
	}
	protected void pushPageDataToValueStack(Object object){
		ActionContext.getContext().getValueStack().push(object);
	}
}
